package com.hdhere.domain.common.rest;

import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dus on 2018/11/4.
 */
public class CallResult extends LinkedHashMap<String, Object> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 响应代码
     */
    private static final String CODE = "code";

    /**
     * 响应消息提示
     */
    private static final String MSG = "msg";

    /**
     * 响应数据域
     */
    private static final String DATA = "data";

    /**
     * 响应分页总页数
     */
    private static final String NEXT_TAG = "next";

    /**
     * 响应分页当前数据列表
     */
    private static final String PAGE_LIST_TAG = "list";

    /**
     * 响应分页分页总数据行数
     */
    private static final String TOTAL_COUNT_TAG = "total";


    public static CallResult fail(){
        return new CallResult().setFail();
    }

    public static CallResult fail(String msg){
        return new CallResult().setFail(msg);
    }

    public static CallResult ok(){
        return new CallResult();
    }

    public static CallResult ok(Object data){
        return new CallResult(data);
    }

    /** 默认构造方法：默认设置返回成功 **/
    public CallResult() {
        super();
        this.put(CODE, StatCode.SUCCESS);
        this.put(MSG, null);
        this.put(DATA, null);
    }

    /** 設置返回數據构造方法：默认设置返回成功
     * 业务逻辑错误直接抛异常，无需手动返回错误结果**/
    public CallResult(Object data) {
        this();
        this.put(DATA, data);
    }

    public CallResult setFail() {
        this.put(CODE, StatCode.FAILURE);
        return this;
    }
    public CallResult setFail(String msg) {
        this.put(MSG, msg);
        return setFail();
    }
    public CallResult setFail(String msg, Object data) {
        this.put(DATA, data);
        return setFail(msg);
    }

    /**
     * 强制客户端重新登录
     * @param warm 警告信息
     */
    public void forceReLogin(String warm){
        this.put(CODE, StatCode.FORCE_RE_LOGIN);
        this.put(MSG, warm);
    }

    public void setMsg(String msg) {
        this.put(MSG, msg);
    }

    public void setData(Object data) {
        this.put(DATA, data);
    }

    public <T> void setData(List<T> list) {
        Map<String, Object> map = new HashMap<>();
        map.put(NEXT_TAG, 0);
        map.put(PAGE_LIST_TAG, list);
        map.put(TOTAL_COUNT_TAG, list.size());
        setData(map);
    }

    /** 响应状态码 **/
    private static class StatCode {
        /** 成功 */
        static final int SUCCESS = 1;
        /** 失败 */
        static final int FAILURE = 0;
        /** 信息过期，强制重新登录 */
        static final int FORCE_RE_LOGIN = -1;
    }

    /** 分页状态码 **/
    private static class PagerCode{
        /** 分页：还有下一页 **/
        static final int HAS_NEXT = 1;
        /** 分页：没有下一页 **/
        static final int NO_NEXT = 0;
    }

}
